import log from "./logger";
import * as mssql from "mssql";
import {NodeCO, TrainAllCO} from "./interface";
import config from "./config";
import sender from "./sender";

function formatTime(date: string, time: string) {
    if (time.trim() === '') {
        return null;
    } else {
        // 拆分输入的时间字符串
        const parts = time.split(':');
        // 确保每部分都已经填充为两位数
        const formattedParts = parts.map(part => part.padStart(2, '0'));
        // 重新拼接成所需的格式
        return date + ' ' + formattedParts.join(':');
    }
}

class XsyTrainWorker {
    init() {
        this.collection().catch((e) => {
            log.info(e);
        });
        setInterval(() => {
            this.collection().catch((e) => {
                log.info(e);
            });
        }, 1000 * 60)
    }

    async collection() {
        const cfg = {
            user: 'sa',
            password: 'Tamj_8926536',
            server: 'SKY-20180529MCO\\SQL',
            database: 'TAMJ',
            port: 1433,
            options: {
                encrypt: false,
            }
        };
        await mssql.connect(cfg);
        try {
            let nodes: NodeCO[] = []
            let train_query_sql = "SELECT top 2 loadDate, CarNum from TD_Load where len(carNum)<=4 group by loadDate , CarNum order by loadDate desc"
            const train_res = await new mssql.Request().query(train_query_sql);
            let length = train_res.recordset.length;
            for (let i = 0; i < length; i++) {
                let train_data = train_res.recordset[i];
                let train_node_query_sql = "SELECT " +
                    "  ID,\n" +
                    "  loadDate,\n" +
                    "  CarNum,\n" +
                    "  CoalType,\n" +
                    "  CarType,\n" +
                    "  CarID,\n" +
                    "  Ratedtare,\n" +
                    "  RatedWeight,\n" +
                    "  ActualWeight,\n" +
                    "  ActualGrossWeight,\n" +
                    "  Difference,\n" +
                    "  LoadTime,\n" +
                    "  carLable,\n" +
                    "  status,\n" +
                    "  line_no\n" +
                    "  FROM TD_Load\n" +
                    "  WHERE\n" +
                    "  loadDate = '" + train_data['loadDate'] + "' and CarNum= '" + train_data['CarNum'] + "'" +
                    "  AND ActualWeight>0\n" +
                    "  ORDER BY line_no\n";
                const train_node_res = await new mssql.Request().query(train_node_query_sql);
                // 总节数小于40的过滤
                if (train_node_res.recordset.length <= 40) {
                    continue;
                }
                let totalWeight = 0;
                let totalMaxWeight = 0;
                let productName = '';
                for (let i = 0; i < train_node_res.recordset.length; i++) {
                    let train_node_data = train_node_res.recordset[i]
                    totalWeight += Number.parseFloat(train_node_data['ActualWeight']) || 0;
                    totalMaxWeight += Number.parseFloat(train_node_data['RatedWeight']) || 0;
                    productName = train_node_data['CoalType']
                    nodes.push({
                        centerDeviation: "",
                        frontBackDiff: "",
                        diffWeight: train_node_data['Difference'],
                        code: train_data['loadDate'] + '-' + train_data['CarNum'] + '-' + train_node_data['line_no'],
                        lable: null,
                        maxNetWeight: train_node_data['RatedWeight'],
                        no: train_node_data['CarID'],
                        sort: train_node_data['line_no'],
                        speed: null,
                        standardTareWeight: null,
                        time: formatTime(train_data['loadDate'], train_node_data['LoadTime']),
                        trainCode: train_data['loadDate'] + '-' + train_data['CarNum'],
                        carType: train_node_data['CarType'],
                        weight: train_node_data['ActualWeight'],
                        containerNumber1: null,
                        containerNumber2: null,
                        containerType1: null,
                        containerType2: null,
                        state: 'Done',
                        createTenantId: null,
                        createTenantName: null
                    });
                }
                log.info("nodes[0]:", nodes[0]);
                // 时间存在中文解析错误的情况
                let startTime = nodes[0]['time'];
                let endTime = nodes[nodes.length - 1]['time'];
                let train: TrainAllCO = {
                    wagonType: 'Gondola',
                    firstNo: nodes[0].no,
                    lastNo: nodes[nodes.length - 1].no,
                    type: "db",
                    totalDiffWeight: totalWeight - totalMaxWeight,
                    totalMaxWeight: totalMaxWeight,
                    totalWeight: totalWeight,
                    boxCount: null,
                    code: train_data['loadDate'] + '-' + train_data['CarNum'],
                    deviceName: config.deviceName,
                    direction: "Leave",
                    name: train_data['loadDate'] + '-' + train_data['CarNum'],
                    no: train_data['loadDate'] + '-' + train_data['CarNum'],
                    nodes: nodes,
                    platformId: config.platformId,
                    platformName: config.platformName,
                    productName: productName,
                    senderName: null,
                    startTime: startTime,
                    endTime: endTime,
                    stationName: null,
                    time: startTime,
                    createTenantId: null,
                    createTenantName: null,
                    totalNode: nodes.length
                }
                // log.info("train:", train);
                try {
                    await sender.send("trainAll", train);
                    nodes = []
                } catch (e) {
                    log.error("err train:", e);
                }
            }
        } catch (e) {
            log.error(e);
        }
    }
}

const xsyTrainWorker = new XsyTrainWorker();
export default xsyTrainWorker;